package com.tanzeer.deliverytracker;

import java.util.ArrayList;

import android.R.string;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tanzeer.deliverytracker.adapter.NavDrawerAdapter;
import com.tanzeer.deliverytracker.adapter.SpinnerItemAdapter;
import com.tanzeer.deliverytracker.dbhelper.DBOpenHelper;
import com.tanzeer.deliverytracker.dbhelper.RelsellDBOpenHelper;
import com.tanzeer.deliverytracker.fragments.Fragment_webview;
import com.tanzeer.deliverytracker.utility.ApplicationVars;
import com.tanzeer.deliverytracker.utility.ApplicationVars.Subscription;

public class MainActivity extends FragmentActivity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private string cat;
	String[] list = { "By Status,Active", "Completed", "By Category", "None" };

	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private NavDrawerAdapter adapter;
	ArrayList<String> drawyerItem = new ArrayList<String>();
	ArrayList<String> spinnerItem = new ArrayList<String>();
	boolean doubleBackToExitPressedOnce = false;
	private static final int BUTTON_POSITIVE = -1;
	private static final int BUTTON_NEGATIVE = -2;
	ActionBar actionBar;
	private Menu myMenu = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		initAppWideVariables();

		setContentView(R.layout.activity_main);
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
		actionBar = getActionBar();
		actionBar.setDisplayShowCustomEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		setDrawyerItems();
		// addDrayerUtems();
		adapter = new NavDrawerAdapter(this, R.layout.nav_drawer_row,
				drawyerItem);
		mDrawerList.setAdapter(adapter);
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				
				if (position == 1 || position == 2 || position > 3) {
					Intent intent = new Intent(getApplicationContext(),
							DeliveryListActivity.class);
					intent.putExtra("type", drawyerItem.get(position));
					if(position>3){
						intent.putExtra("type","Category");
						intent.putExtra("categoryName", drawyerItem.get(position));
					}
					
					startActivity(intent);

				}

			}
		});

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_navigation_drawer, // nav menu toggle icon
				R.string.app_name, // nav drawer open - description for
									// accessibility
				R.string.app_name // nav drawer close - description for
									// accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		// change layout
		Fragment_webview fragment_webview = new Fragment_webview();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.frame_container, fragment_webview).commit();

	}

	private void setDrawyerItems() {
		drawyerItem.add("By Status");
		drawyerItem.add("Active");
		drawyerItem.add("Completed");
		try {
			RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(
					MainActivity.this);
			ArrayList<String> templist = dbHelper
					.getListDataForNavigationDrawer();

			if (templist.size() > 0)
				drawyerItem.add("By Category");

			int i;
			for (i = 0; i < templist.size(); i++) {
				drawyerItem.add(templist.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void addDrayerUtems() {
		DBOpenHelper dbHelper = new DBOpenHelper(MainActivity.this);
		ArrayList<String> templist = dbHelper.getActiveCategoryList();
		int i;
		for (i = 0; i < templist.size(); i++) {
			drawyerItem.add(templist.get(i));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		myMenu = menu;
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		// menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {

		case R.id.nav_add: {
			showAddDialog();
			return true;
		}
		case R.id.exit: {

			/*
			 * Intent intent = new Intent(this, DemoActivity.class);
			 * intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
			 * Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
			 * startActivity(intent); finish();
			 */
			showExitDialog();
			return true;

		}
		case R.id.settings: {
			Intent intent = new Intent(getApplicationContext(),
					SettingsActivity2.class);
			intent.putExtra("activity", 0);
			startActivity(intent);
			return true;
		}
		case R.id.about: {
			
			Intent intent = new Intent(getApplicationContext(),
					AboutActivity.class);
			intent.putExtra("activity", 0);
			startActivity(intent);
			return true;

		}
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void setSearchDialog() {

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.action_bar_serach, null);
		actionBar.setCustomView(v);

	}

	private void setNavAdapter() {

		adapter.notifyDataSetChanged();
		adapter = new NavDrawerAdapter(this, R.layout.nav_drawer_row,
				drawyerItem);
		adapter.notifyDataSetInvalidated();
		// this.onCreate(null);
	}

	private void showAddDialog() {
		final Dialog dialog = new Dialog(MainActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.addcontent);
		final EditText edtPkgNumber = (EditText) dialog
				.findViewById(R.id.editText1);
		final EditText edtPkgDescription = (EditText) dialog
				.findViewById(R.id.editText2);
		final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner1);
		setSpinnerItem();
		SpinnerItemAdapter adapter = new SpinnerItemAdapter(
				getApplicationContext(), R.layout.spinner_row_view_custom,
				spinnerItem);
		spinner.setAdapter(adapter);

		Button btnOk = (Button) dialog.findViewById(R.id.button2);
		Button btnCancel = (Button) dialog.findViewById(R.id.button1);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String tracknumber = edtPkgNumber.getText().toString();
				String description = edtPkgDescription.getText().toString();
				String category = spinner.getSelectedItem().toString();
				String status = "NOT DELIVERED";
				if (!tracknumber.equals("") && !description.equals("")
						&& !category.equals("")) {
					if (ApplicationVars.getInstance().isSubscribed()) {
						RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(
								MainActivity.this);
						dbHelper.openDb();
						int res = dbHelper.saveDelivery(description,tracknumber, category, status); // TODO:
																				// we
																				// can
																				// add
																				// package
																				// description
						// here
						if (res == 1) {
							if (!drawyerItem.contains("By Category"))
								drawyerItem.add("By Category");
							if (!drawyerItem.contains(category)) {
								drawyerItem.add(category);
								Log.e("msg", "" + drawyerItem.size());
								toast("Data Saved");
							}
						} else {
							toast("subcription limit is reached");
						}
					} else {
						ApplicationVars.getInstance().getSubscriptionObject()
								.setSubscrtionTypeInteger(30);
						toast("subcription required to save more tracks");
					}

					dialog.dismiss();

				} else
					toast("Some fields are empty");
				
				Intent intent = new Intent(getApplicationContext(),
						DeliveryListActivity.class);
				intent.putExtra("type","Active");
				startActivity(intent);
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private void toast(String str) {
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onBackPressed() {

		if (doubleBackToExitPressedOnce) {
			super.onBackPressed();
			// TODO : commit DB changes
			return;
		}

		this.doubleBackToExitPressedOnce = true;
		Toast.makeText(this, "Please click BACK again to exit",
				Toast.LENGTH_SHORT).show();

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce = false;
			}
		}, 2000);
	}

	private void setSpinnerItem() {
		spinnerItem.add("None");
		spinnerItem.add("Incoming");
		spinnerItem.add("Outgoing");
		spinnerItem.add("Favorite");
		spinnerItem.add("Important");
		spinnerItem.add("Movie");
		spinnerItem.add("Gift");
		spinnerItem.add("Heart");
		spinnerItem.add("Business");
		spinnerItem.add("Camera");
		spinnerItem.add("Clothes");
		spinnerItem.add("Computer");
		spinnerItem.add("Games");
		spinnerItem.add("Food Dishes");
		spinnerItem.add("Light");
		spinnerItem.add("Music");
		spinnerItem.add("Office Materials");
		spinnerItem.add("Paint");
		spinnerItem.add("Medicine");
		spinnerItem.add("Flowers");
		spinnerItem.add("Sports");
		spinnerItem.add("Tools");
	}

	private void exit() {

		Intent intent = new Intent(this, DemoActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_CLEAR_TASK
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		finish();

	}

	private void showExitDialog() {

		AlertDialog Alert = new AlertDialog.Builder(MainActivity.this).create();
		Alert.setTitle("Exit");
		Alert.setMessage("Want to close?");

		Alert.setButton(BUTTON_POSITIVE, "Exit",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						exit();
						dialog.dismiss();
						// to do
					}
				});

		Alert.setButton(BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();

					}
				});
		Alert.show();
	}

	private void ShowAboutDiallog() {
		final Dialog dialog = new Dialog(MainActivity.this);

		dialog.setContentView(R.layout.dialog_about);
		dialog.setTitle("Like Track My Packages?");
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		TextView txtNotNow = (TextView) dialog.findViewById(R.id.textView5);
		TextView textrate = (TextView) dialog.findViewById(R.id.textView4);
		Spannable txtlabel = new SpannableString(
				"Rate Track My Packages on   Google Play");
		// Bitmap smiley = BitmapFactory.decodeResource( getResources(),
		// R.drawable.play);
		txtlabel.setSpan(
				new ImageSpan(getApplicationContext(), R.drawable.play), 26,
				27, 0);
		textrate.setText(txtlabel);
		textrate.setGravity(Gravity.TOP);

		txtNotNow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();

			}
		});
		dialog.show();
		dialog.getWindow().setLayout(metrics.widthPixels, metrics.heightPixels);
	}
	
	
	private void initAppWideVariables() {
		ApplicationVars.getInstance().setSubscribed(true);
		int subscriptionValue = 30;
		ApplicationVars.getInstance().setSubscriptionObject(ApplicationVars.getInstance().new Subscription(subscriptionValue));
	}

}
